package com.coocaa.ops.admin.v1.mergeposter.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.coocaa.ops.admin.base.exception.AdminBizException;
import com.coocaa.ops.plus.core.third.magic.model.AiIconInfoModel;
import com.coocaa.ops.plus.core.third.magic.model.BlockPositionInfo;
import com.coocaa.ops.plus.core.third.magic.model.OriginMergeInfo;
import com.coocaa.ops.admin.v1.mergeposter.constant.PublishStatusConstants;
import com.coocaa.ops.admin.v1.mergeposter.model.internal.AiPosterMergeDbInfo;
import com.coocaa.ops.admin.v1.mergeposter.model.internal.BasePosterMergeInfo;
import com.coocaa.ops.admin.v1.mergeposter.validator.PosterMergeValidator;
import com.coocaa.ops.common.core.biz.layout.constant.LayoutTypeConstants;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.json.JsonUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author bjh
 * @description
 * @date 2021/1/7 10:55
 */
@Slf4j
@UtilityClass
public class PosterMergeDataHandler {

    public static OriginMergeInfo getOriginMergeInfo(AiPosterMergeDbInfo aiPosterMergeDbInfo) {
        OriginMergeInfo originMergeInfo = new OriginMergeInfo(aiPosterMergeDbInfo.getPictureUrl(), aiPosterMergeDbInfo.getBlockPositionInfo());
        List<AiIconInfoModel> iconTextPositions = JsonUtil.json2ObjectLists(aiPosterMergeDbInfo.getIconTextPositionsJsonStr(), AiIconInfoModel.class);
        originMergeInfo.setIconTextPositions(iconTextPositions);
        if (PosterMergeValidator.isCanNotDrawText(aiPosterMergeDbInfo)) {
            return originMergeInfo;
        }
        boolean isShowTitle = PosterMergeValidator.isShowTitle(aiPosterMergeDbInfo);
        if (isShowTitle) {
            originMergeInfo.setTitle(aiPosterMergeDbInfo.getTitle());
        }
        String subTitle = getFinalSubTitle(aiPosterMergeDbInfo);
        boolean isShowSubTitle = PosterMergeValidator.isShowSubTitle(aiPosterMergeDbInfo, subTitle);
        if (isShowSubTitle) {
            originMergeInfo.setSubtitle(subTitle);
        }
        boolean isShowSeries = PosterMergeValidator.isShowSeries(aiPosterMergeDbInfo);
        boolean isShowVariety = false;
        if (isShowSeries) {
            String serial = getSeriesInfo(aiPosterMergeDbInfo);
            originMergeInfo.setScore(serial);
        } else {
            isShowVariety = PosterMergeValidator.isShowVariety(aiPosterMergeDbInfo);
            if (isShowVariety) {
                originMergeInfo.setScore(aiPosterMergeDbInfo.getVariety());
            }
        }
        boolean isShowScore = PosterMergeValidator.isShowScore(isShowSeries, aiPosterMergeDbInfo, isShowVariety);
        if (isShowScore) {
            String score = getScore(aiPosterMergeDbInfo);
            originMergeInfo.setScore(score);
        }
        return originMergeInfo;
    }

    public static String getFinalSubTitle(BasePosterMergeInfo posterMergeInfo) {
        String subTitle = StringUtils.isNotBlank(posterMergeInfo.getSingleSubTitle()) ? posterMergeInfo.getSingleSubTitle() : posterMergeInfo.getSubTitle();
        return subTitle;
    }

    /**
     * 合成海报-推荐位位置处理-UI8.0布局
     *
     * @param layoutJson8
     * @param aiPosterMergeDbInfoList
     */
    public static List<AiPosterMergeDbInfo> handleMergePosterBlockPos(String layoutJson8, List<AiPosterMergeDbInfo> aiPosterMergeDbInfoList) {
        if (StringUtils.isBlank(layoutJson8)) {
            return null;
        }
        try {
            JSONObject layoutJson = JSON.parseObject(layoutJson8);
            String type = layoutJson.getString("type");
            Assert.notNull(type, "解析布局的type不能为空！");
            JSONArray layoutList = layoutJson.getJSONArray("contents");
            if (CollectionUtils.isEmpty(layoutList)) {
                return null;
            }
            TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap = convert2TreeMapByNormalSpecialFlag(aiPosterMergeDbInfoList);
            if (blockDataTreeMap.isEmpty()) {
                return null;
            }
            switch (type) {
                case LayoutTypeConstants.PANEL:
                    handlePanelLayout(blockDataTreeMap, layoutList);
                    break;
                case LayoutTypeConstants.EXPANDER:
                    handleExpanderLayout(blockDataTreeMap, layoutList);
                    break;
                case LayoutTypeConstants.LENGTHWISE:
                    handleLengthwiseLayout(blockDataTreeMap, layoutList);
                    break;
                default:
                    throw new AdminBizException("没有对应type的布局处理,type=" + type);

            }
            return convert2List(blockDataTreeMap);
        } catch (Exception e) {
            log.error(ExceptionUtil.getErrorPrintLog("合成海报", e.getMessage(), ExceptionUtil.getStackTraceAsString(e)));
            return null;
        }
    }

    private static List<AiPosterMergeDbInfo> convert2List(TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap) {
        List<AiPosterMergeDbInfo> result = InstanceUtil.newArrayList();
        for (Map.Entry<Integer, List<AiPosterMergeDbInfo>> entry : blockDataTreeMap.entrySet()) {
            List<AiPosterMergeDbInfo> tempList = entry.getValue();
            result.addAll(tempList);
        }
        return result;
    }

    private static TreeMap<Integer, List<AiPosterMergeDbInfo>> convert2TreeMapByNormalSpecialFlag(List<AiPosterMergeDbInfo> aiPosterMergeDbInfoList) {
        TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap = new TreeMap<>();
        for (AiPosterMergeDbInfo aiPosterMergeDbInfo : aiPosterMergeDbInfoList) {
            if (null == aiPosterMergeDbInfo || aiPosterMergeDbInfo.getBlockId() == null) {
                continue;
            }
            List<AiPosterMergeDbInfo> existBlockDataList = blockDataTreeMap.get(aiPosterMergeDbInfo.getBlockSeq());
            if (null == existBlockDataList) {
                existBlockDataList = InstanceUtil.newArrayList();
                existBlockDataList.add(aiPosterMergeDbInfo);
                blockDataTreeMap.put(aiPosterMergeDbInfo.getBlockSeq(), existBlockDataList);
            } else {
                existBlockDataList.add(aiPosterMergeDbInfo);
            }
        }
        return blockDataTreeMap;
    }


    private static void handlePanelLayout(TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap, JSONArray layoutList) {
        for (Map.Entry<Integer, List<AiPosterMergeDbInfo>> entry : blockDataTreeMap.entrySet()) {
            handleBlockLayout(entry.getValue(), layoutList.getJSONObject(entry.getKey() - 1));
        }
    }

    private static void handleLengthwiseLayout(TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap, JSONArray layoutList) {
        //纵向扩展布局的取一个进行处理即可，宽高是标准的
        JSONObject blockPosJson = layoutList.getJSONObject(0);
        for (Map.Entry<Integer, List<AiPosterMergeDbInfo>> entry : blockDataTreeMap.entrySet()) {
            handleBlockLayout(entry.getValue(), blockPosJson);
        }
    }

    private static void handleBlockLayout(List<AiPosterMergeDbInfo> blockDataModelList, JSONObject eachBlockPos) {
        BlockPositionInfo blockPositionInfo = getBlockPositionInfo(eachBlockPos);
        String blockTitlePosition = getBlockTitlePositionJson(eachBlockPos);
        for (AiPosterMergeDbInfo blockDataModel : blockDataModelList) {
            blockDataModel.setBlockPositionInfo(blockPositionInfo);
            blockDataModel.setBlockTitlePosition(blockTitlePosition);
        }
    }

    private static void handleExpanderLayout(TreeMap<Integer, List<AiPosterMergeDbInfo>> blockDataTreeMap, JSONArray layoutList) {
        int count = layoutList.size();
        if (count == 1) {
            //正常横向拓展
            for (Map.Entry<Integer, List<AiPosterMergeDbInfo>> entry : blockDataTreeMap.entrySet()) {
                handleBlockLayout(entry.getValue(), layoutList.getJSONObject(0));
            }
        }
        if (count == 2) {
            //异形横向拓展
            int index = 0;
            for (Map.Entry<Integer, List<AiPosterMergeDbInfo>> entry : blockDataTreeMap.entrySet()) {
                if (index == 0) {
                    handleBlockLayout(entry.getValue(), layoutList.getJSONObject(0));
                } else {
                    handleBlockLayout(entry.getValue(), layoutList.getJSONObject(1));
                }
                index++;
            }
        }
    }

    /**
     * 获取推荐位的位置信息
     *
     * @param eachBlockPos
     * @return
     */
    private static BlockPositionInfo getBlockPositionInfo(JSONObject eachBlockPos) {
        Integer width = eachBlockPos.getInteger("width");
        Integer height = eachBlockPos.getInteger("height");
        return new BlockPositionInfo(width, height);

    }

    private static String getScore(AiPosterMergeDbInfo posterMergeDbInfo) {
        String score = posterMergeDbInfo.getScore();
        if (StringUtils.isNotBlank(score) && score.length() == 1) {
            //对于只有一位的，补上.0
            score = score + ".0";
        }
        return score;
    }

    private static String getSeriesInfo(AiPosterMergeDbInfo posterMergeDbInfo) {
        String text = "更新到" + posterMergeDbInfo.getSeries() + "集";
        if (PublishStatusConstants.isEnded(posterMergeDbInfo.getPublishStatus())) {
            text = "全" + posterMergeDbInfo.getSeries() + "集";
        }
        return text;
    }

    /**
     * 获取标题的位置信息
     *
     * @param eachBlockPos
     * @return
     */
    private static String getBlockTitlePositionJson(JSONObject eachBlockPos) {
        String blockTitlePosition = eachBlockPos.getString("title_info");
        blockTitlePosition = blockTitlePosition == null ? "" : blockTitlePosition;
        return blockTitlePosition;
    }

}
